#include "stdafx.h"
#include "Address.h"

Address::Address(void){
	memset(&m_address, 0, sizeof(m_address));
	m_address.sin_family = AF_INET;
	m_address.sin_addr.s_addr =htonl(INADDR_ANY);
	m_address.sin_port= htons(DEFAULT_SERVER_PORT);
}

Address::Address(WSSOCKADDRESS& address){	//:m_address(address)
	memset(&m_address, 0, sizeof(m_address));
	m_address.sin_family = address.sin_family;
	m_address.sin_addr.S_un=address.sin_addr.S_un;
	m_address.sin_port= address.sin_port;
}

Address::Address(TCHAR* ipv4,WSPORT port){
	memset(&m_address, 0, sizeof(m_address));
	m_address.sin_family = AF_INET;
	USES_CONVERSION ;
	char* addr=T2A(ipv4);
	m_address.sin_addr.s_addr = inet_addr(addr); 
	m_address.sin_port= htons(port);
}

Address::Address(TCHAR* ipv4){
	memset(&m_address, 0, sizeof(m_address));
	m_address.sin_family = AF_INET;
	USES_CONVERSION ;
	char* addr=T2A(ipv4);
	m_address.sin_addr.s_addr = inet_addr(addr); 
	m_address.sin_port= htons(DEFAULT_SERVER_PORT);
}

Address::~Address(void)
{
}

WSSOCKADDRESS Address::getAddress(){
	return this->m_address;
}
BOOL Address::getAddressString(TCHAR* addressString,LEN lenOfAddressString){
	if(addressString==NULL ||lenOfAddressString==0) return FALSE;
	char* tmp=inet_ntoa(m_address.sin_addr);
	USES_CONVERSION ;
	TCHAR* szIp=A2T(tmp);
	_tcscpy_s(addressString,lenOfAddressString,szIp);
	return _tcslen(szIp);
}
WSPORT Address::getPort(){
	return ntohs(this->m_address.sin_port);
}

int Address::ToString(TCHAR* result,size_t resultSize){
	char* tmp=inet_ntoa(m_address.sin_addr);
	size_t ipLen=strlen(tmp);
	USES_CONVERSION ;
	TCHAR* szIp=A2T(tmp);
	TCHAR sz[STRLEN_SMALL]={0};
	_stprintf_s(sz,L"%s:%d",szIp,getPort());
	size_t len=_tcslen(sz);
	if(result==NULL || resultSize<=len){
		return len;
	}else{
		_tcscpy_s(result,resultSize,sz);
		return resultSize;
	}
}